<template>
  <a-modal
    v-model:visible="passwordModal"
    title="修改密码"
    @cancel="handleCancel"
    @before-ok="clickOk"
  >
    <a-form ref="formRef" :model="form" :rules="rules">
      <a-form-item field="oldPassword" label="原始密码" validate-trigger="blur">
        <a-input v-model="form.oldPassword" placeholder="原始密码" />
      </a-form-item>
      <a-form-item field="newPassword" label="新密码" validate-trigger="blur">
        <a-input-password
          v-model="form.newPassword"
          placeholder="请输入新密码"
          allow-clear
        />
      </a-form-item>
      <a-form-item
        field="passwordAgain"
        label="确认新密码"
        validate-trigger="blur"
      >
        <a-input-password
          v-model="form.passwordAgain"
          placeholder="请再次输入新密码"
          allow-clear
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue';
  import { changePassword } from '@/api/user';
  import { Notification } from '@arco-design/web-vue';
  import router from '@/router';
  import { useBooleanStore } from '@/store';

  const booleanStore = useBooleanStore();
  const formRef = ref<any>('');
  const passwordModal = ref<boolean>(false);
  const form = reactive({
    oldPassword: '',
    newPassword: '',
    passwordAgain: '',
  });
  const rules = {
    oldPassword: [{ required: true, message: '原始密码不能为空' }],
    newPassword: [
      { required: true, message: '新密码不能为空' },
      {
        validator: (value: string, cb: any) => {
          if (value.length < 6) {
            cb('密码长度不能小于6');
          } else {
            cb();
          }
        },
      },
    ],
    passwordAgain: [
      { required: true, message: '确认新密码不能为空' },
      {
        validator: (value: string, cb: any) => {
          if (value !== form.newPassword) {
            cb('两次密码输入不一致');
          } else {
            cb();
          }
        },
      },
    ],
  };
  async function clickOk(done: any) {
    const status = await formRef.value.validate();
    if (status) {
      done(false);
    } else {
      const data = await changePassword({
        oldPwd: form.oldPassword,
        newPwd: form.passwordAgain,
      });
      if (data.retCode === '200') {
        Notification.success({
          title: '成功',
          content: data.message,
          closable: true,
        });
      } else {
        Notification.error({
          title: '失败',
          content: data.message,
          closable: true,
        });
      }
      router.push({
        name: 'login',
      });
      booleanStore.toggleMenu();
      done();
    }
  }
  const handleCancel = () => {
    passwordModal.value = false;
    form.newPassword = '';
    form.oldPassword = '';
    form.passwordAgain = '';
  };
</script>
